<script setup lang="ts">
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const route = useRoute();
const editFormRef = ref();

const connectionId = computed(() => route.query.connectionId as string);
const initialData = reactive({
  id: (route.query.id as string) || '',
  ip: (route.query.ip as string) || '',
  port: parseInt(route.query.port as string) || 443,
  label: (route.query.label as string) || ''
});

const editForm = reactive({
  label: initialData.label,
  ip: initialData.ip,
  port: initialData.port
});

const editFormRules = computed(() => ({
  label: [{ required: true, message: t('HOME_EDIT_CONNECTION_LABEL_REQUIRED'), trigger: 'blur' }],
  ip: [
    { required: true, message: t('LOGIN_IP_REQUIRED'), trigger: 'blur' },
    {
      pattern: /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/,
      message: t('LOGIN_IP_INVALID'),
      trigger: 'blur'
    }
  ],
  port: [
    { required: true, message: t('LOGIN_PORT_REQUIRED'), trigger: 'blur' },
    {
      type: 'number',
      min: 1,
      max: 65535,
      message: t('LOGIN_PORT_RANGE'),
      trigger: 'blur'
    }
  ]
}));

const handleSave = async () => {
  if (!editFormRef.value) return;

  try {
    const valid = await editFormRef.value.validate();
    if (!valid) return;

    if (window.api?.ipc?.send) {
      window.api.ipc.send('edit-connection-save', {
        connectionId: connectionId.value,
        data: {
          id: initialData.id,
          ip: editForm.ip,
          port: editForm.port,
          label: editForm.label
        }
      });
    }
  } catch (error) {
    console.error('Form validation failed:', error);
  }
};

const handleCancel = () => {
  if (window.api?.ipc?.send) {
    window.api.ipc.send('edit-connection-cancel', connectionId.value);
  }
};

const handleKeyDown = (event: KeyboardEvent) => {
  if (event.key === 'Escape') {
    handleCancel();
  } else if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
    handleSave();
  }
};

onMounted(() => {
  window.addEventListener('keydown', handleKeyDown);
});

onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleKeyDown);
});
</script>

<template>
  <div class="edit-connection-container">
    <div class="edit-connection-header">
      <h3>{{ $t('HOME_EDIT_CONNECTION') }}</h3>
    </div>
    <div class="edit-connection-content">
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item :label="$t('HOME_EDIT_CONNECTION_LABEL')" prop="label">
          <el-input
            v-model="editForm.label"
            :placeholder="$t('HOME_EDIT_CONNECTION_LABEL_PLACEHOLDER')"
            clearable
            autofocus
          />
        </el-form-item>
        <el-form-item :label="$t('LOGIN_IP')" prop="ip">
          <el-input
            v-model="editForm.ip"
            :placeholder="$t('LOGIN_IP_PLACEHOLDER') || '请输入IP地址'"
            clearable
          />
        </el-form-item>
        <el-form-item :label="$t('LOGIN_PORT')" prop="port">
          <el-input
            v-model.number="editForm.port"
            :placeholder="$t('LOGIN_PORT_PLACEHOLDER') || '请输入端口'"
            clearable
            type="number"
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="edit-connection-footer">
      <el-button @click="handleCancel">{{ $t('COMMON_CANCEL') }}</el-button>
      <el-button type="primary" @click="handleSave">{{ $t('COMMON_SAVE') }}</el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.edit-connection-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100vh;
  min-height: 100vh;
  background: #fff;
  overflow: hidden;
}

.edit-connection-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e4e7ed;

  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}

.edit-connection-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;

  :deep(.el-form-item) {
    margin-bottom: 22px;
  }

  :deep(.el-input) {
    width: 100%;
  }
}

.edit-connection-footer {
  padding: 16px 24px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  background: #fafafa;
}
</style>
